package com.example.gobang.api;

import com.example.gobang.game.*;
import com.example.gobang.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;



@Component
public class MatchApi extends TextWebSocketHandler {


    private ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private OnlineUserManager onlineUserManager;

    @Autowired
    private Match match;
    @Autowired
    private AiMatch aiMatch;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //玩家上线，加入到onlineUserManager中
        try {
            //获取用户信息
            User user = (User) session.getAttributes().get("user");
            //判断用户多开情况
            if (onlineUserManager.getFromGameHall(user.getUserId()) != null
                    || onlineUserManager.getFromGameRoom(user.getUserId()) != null){
                MatchResponse response = new MatchResponse();
                response.setOk(true);
                response.setReason("账号已在其他地方登入");
                response.setMessage("repeatConnection");
                session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
                session.close();
                return;
            }
            //进入成功
            onlineUserManager.enterGameHall(user.getUserId(),session);
            System.out.println("玩家 "+user.getUsername()+"进入了大厅");
        }catch (NullPointerException e){//空指针异常 说明用户未登入
            System.out.println("[MatchApi]:用户未登入");
            /*e.printStackTrace();
            MatchResponse matchResponse = new MatchResponse();
            matchResponse.setOk(false);
            matchResponse.setReason("用户未登入");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchResponse)));*/
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //获取用户信息
        User user = (User) session.getAttributes().get("user");
        //处理匹配
        String payload = message.getPayload();
        MatchRequest request = objectMapper.readValue(payload, MatchRequest.class);//将json转换为对象
        MatchResponse response = new MatchResponse();
        if (request.getMessage().equals("startMatch")){
            //进入匹配队列
            match.add(user);
            //加入完成后，给客户端一个响应
            response.setOk(true);
            response.setMessage("startMatch");
        } else if (request.getMessage().equals("stopMatch")) {
            //退出匹配队列
            match.remove(user);
            //退出成功后，给客户端一个响应
            response.setOk(true);
            response.setMessage("stopMatch");
        } else if (request.getMessage().equals("aiMatch")) {//Ai对局
            aiMatch.add(user);
            // 4. 给玩家 发回响应数据
            response.setOk(true);
            response.setMessage("aiMatch");
        } else {//非法情况
            response.setOk(false);
            response.setReason("非法的匹配情况");
        }
        synchronized (session){
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        try {
            User user = (User) session.getAttributes().get("user");
            //防止用户多开，当登入的账号的 WebSocketSession 和退出账号的 WebSocketSession 相等时才退出游戏大厅
            WebSocketSession tempSession = onlineUserManager.getFromGameHall(user.getUserId());
            if (tempSession == session){
                onlineUserManager.exitGameHall(user.getUserId());
            }
        }catch (NullPointerException e){
            System.out.println("[handleTransportError]:当前用户未登入");
            /*e.printStackTrace();
            MatchResponse matchResponse = new MatchResponse();
            matchResponse.setOk(false);
            matchResponse.setReason("您尚未登入！");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchResponse)));*/
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        try {
            User user = (User) session.getAttributes().get("user");
            //防止用户多开，当登入的账号的 WebSocketSession 和退出账号的 WebSocketSession 相等时才退出游戏大厅
            WebSocketSession tempSession = onlineUserManager.getFromGameHall(user.getUserId());
            if (tempSession == session){
                onlineUserManager.exitGameHall(user.getUserId());
            }
        }catch (NullPointerException e){
            System.out.println("[afterConnectionClosed]:当前用户未登入");
            //e.printStackTrace();
            /*MatchResponse matchResponse = new MatchResponse();
            matchResponse.setOk(false);
            matchResponse.setReason("您尚未登入！");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchResponse)));*/
        }
    }


}
